#!/usr/bin/env python3
"""
WebSocket功能演示
"""
import sys
import os
from datetime import datetime

sys.path.insert(0, os.path.dirname(__file__))

from idea_proxy import IDEAProxy
from simple_dashboard_fixed import SimpleDashboard

print("🔌 WebSocket支持功能演示")
print("=" * 60)

# 创建代理实例
proxy = IDEAProxy('127.0.0.1', 8080)

# 添加混合类型的测试数据
test_requests = [
    # 普通HTTP请求
    {
        'timestamp': datetime.now().isoformat(),
        'client_addr': '127.0.0.1:12345',
        'method_line': 'GET https://plugins.jetbrains.com/api/plugins HTTP/1.1',
        'headers': {
            'User-Agent': 'IntelliJ IDEA/2023.3',
            'Host': 'plugins.jetbrains.com',
            'Accept': 'application/json'
        },
        'raw_request': 'GET https://plugins.jetbrains.com/api/plugins HTTP/1.1'
    },
    # WebSocket升级请求 1
    {
        'timestamp': datetime.now().isoformat(),
        'client_addr': '127.0.0.1:12346',
        'method_line': 'GET /socket.io/?transport=websocket HTTP/1.1',
        'headers': {
            'Host': 'ws.jetbrains.com',
            'Upgrade': 'websocket',
            'Connection': 'Upgrade',
            'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
            'Sec-WebSocket-Version': '13',
            'Sec-WebSocket-Protocol': 'socketio',
            'User-Agent': 'IntelliJ IDEA/2023.3'
        },
        'raw_request': 'GET /socket.io/?transport=websocket HTTP/1.1'
    },
    # CONNECT请求
    {
        'timestamp': datetime.now().isoformat(),
        'client_addr': '127.0.0.1:12347',
        'method_line': 'CONNECT plugins.jetbrains.com:443 HTTP/1.1',
        'headers': {
            'User-Agent': 'IntelliJ IDEA/2023.3',
            'Host': 'plugins.jetbrains.com'
        },
        'raw_request': 'CONNECT plugins.jetbrains.com:443 HTTP/1.1'
    },
    # WebSocket升级请求 2
    {
        'timestamp': datetime.now().isoformat(),
        'client_addr': '127.0.0.1:12348',
        'method_line': 'GET wss://ide-services.jetbrains.com/websocket HTTP/1.1',
        'headers': {
            'Host': 'ide-services.jetbrains.com',
            'Upgrade': 'websocket',
            'Connection': 'keep-alive, Upgrade',
            'Sec-WebSocket-Key': 'x3JJHMbDL1EzLkh9GBhXDw==',
            'Sec-WebSocket-Version': '13',
            'User-Agent': 'IntelliJ IDEA/2023.3'
        },
        'raw_request': 'GET wss://ide-services.jetbrains.com/websocket HTTP/1.1'
    }
]

# 添加测试数据
for req in test_requests:
    proxy.requests_log.append(req)

# 模拟活跃的WebSocket连接
proxy.websocket_connections = {
    'ws.jetbrains.com:443_1234567890': {
        'host': 'ws.jetbrains.com',
        'port': 443,
        'start_time': datetime.now().isoformat()
    }
}

print("✅ 已添加测试数据:")
print(f"   📊 总请求: {len(test_requests)}")

# 统计WebSocket请求
websocket_count = 0
for req in test_requests:
    if proxy.is_websocket_request(str(req)):
        websocket_count += 1

print(f"   🔌 WebSocket请求: {websocket_count}")
print(f"   🟢 活跃WebSocket连接: {len(proxy.websocket_connections)}")
print()

print("🔍 请求分析:")
for i, req in enumerate(test_requests, 1):
    method_line = req['method_line']
    headers = req['headers']
    
    is_websocket = (
        headers.get('Upgrade', '').lower() == 'websocket' and
        'upgrade' in headers.get('Connection', '').lower() and
        'Sec-WebSocket-Key' in headers
    )
    
    print(f"  {i}. {method_line}")
    print(f"     类型: {'🔌 WebSocket' if is_websocket else '📡 HTTP'}")
    if is_websocket:
        print(f"     密钥: {headers.get('Sec-WebSocket-Key', 'N/A')}")
        if 'Sec-WebSocket-Protocol' in headers:
            print(f"     协议: {headers['Sec-WebSocket-Protocol']}")
    print()

print("🎨 Dashboard新功能:")
print("   📈 WebSocket统计显示")
print("   🔌 WebSocket请求图标标识")
print("   🎯 WebSocket行蓝色高亮")
print("   📊 活跃连接实时统计")
print()

# 启动dashboard
dashboard = SimpleDashboard(proxy, 8086)
dashboard.start()

print("🚀 WebSocket演示Dashboard已启动!")
print("🌐 现在可以查看WebSocket功能展示")
print()
print("🎯 观察要点:")
print("   - 统计区显示WebSocket请求数和活跃连接数")
print("   - WebSocket请求显示🔌图标和蓝色背景")
print("   - 可以通过URL过滤功能筛选WebSocket请求")
print()
print("⏹️  按Ctrl+C停止演示")

try:
    import time
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("\n⏹️  正在停止演示...")
    dashboard.stop()
    print("✅ 演示已停止")
    print("🎉 WebSocket支持功能演示完成！")